package com.ssau.expert.gui.common;

import com.ssau.expert.app.ExpertAPI;
import com.ssau.expert.common.SuggestedResult;
import com.ssau.expert.entity.Ship;
import com.ssau.expert.exception.NotInitializedException;
import com.ssau.expert.exception.RuleParseException;
import com.ssau.expert.exception.SemanticException;
import com.ssau.expert.gui.app.Locator;
import com.ssau.expert.gui.master.ExpertFrame;
import com.ssau.expert.gui.master.ExpertPresenter;
import com.ssau.expert.gui.user.UserFrame;
import com.ssau.expert.gui.user.UserPresenter;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * Author: Sergey Saiyan
 * Created: 05.09.13 12:58
 */
public class Controller {

    private ExpertAPI expert;
    private ExpertPresenter expertPresenter;
    private UserPresenter userPresenter;
    private LoginFrame loginFrame;

    public void init() {
        expertPresenter.init();
        userPresenter.init();
        expert.setQuestionRequestListener(userPresenter);

        loginFrame.setVisible(true);
    }

    public void showExpertFrame() {
        expertPresenter.showFrame();
    }

    public void showUserFrame() {
        userPresenter.showFrame();
    }

    public void showLoginFrame() {
        loginFrame.showFrame();
    }

    @SuppressWarnings("unchecked")
    public void uploadRules() {
        File f = MyControls.OpenFileDialog(expertPresenter.asFrame());
        if (f == null) {
            return;
        }
        try {
            expert.uploadFileWithRules(f);
            expertPresenter.displayRules(Collections.<String>emptyList());
            List<String> rules = expert.getDatabase().getRules();
            //expertPresenter.enableStartConsultation(!rules.isEmpty());
            expertPresenter.displayRules(rules);
        } catch (IOException | SemanticException | RuleParseException e) {
            expertPresenter.showMessageDialog(e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    public void startConsultation() {
        try {
            expert.initExpertSystem();
        } catch (NotInitializedException ex) {
            userPresenter.showMessageDialog(ex.getMessage());
            return;
        }

        userPresenter.clearResultListModel();

        SuggestedResult suggestedResult;

        suggestedResult = expert.getResult();

        if (suggestedResult == null) {
            userPresenter.addElementToResultList("Решение не было найдено");
        } else {
            if (suggestedResult.getError() == null) {
                userPresenter.addElementToResultList("Предложенный корабль :");
                userPresenter.addElementToResultList(suggestedResult.getSuggestedShip() != null
                        ? suggestedResult.getSuggestedShip().getName()
                        : "Нет единственного решения");
                userPresenter.addElementToResultList("Альтернативные корабли : ");
                for (Ship ship : suggestedResult.getAlternateShips()) {
                    userPresenter.addElementToResultList(ship.getName());
                }
                if (suggestedResult.getAlternateShips().isEmpty()) {
                    userPresenter.addElementToResultList("Альтернатив нет");
                }
            } else {
                userPresenter.addElementToResultList("В ходе консультации произошла ошибка");
            }
        }

        userPresenter.displayUserInput(expert.getShipProfileAnswer(),
                expert.getStaffAnswer(), expert.getDistanceAnswer());
    }

    public static Controller get() {
        return instance;
    }

    private static Controller instance = new Controller();

    private Controller() {
        expert = Locator.getExpert();
        expertPresenter = ExpertFrame.get();
        loginFrame = new LoginFrame();
        userPresenter = UserFrame.get();
    }
}
